﻿using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace MoocProject
{
    class CookieConverter:JsonConverter<Cookie>
    {
		public override Cookie Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			string name = null;
			string value = null;
			string domain = null;
			string path = null;
			DateTime? expiry = null;
			bool secure = false;
			bool httpOnly = false;

			while (reader.Read())
			{
				if (reader.TokenType == JsonTokenType.EndObject)
				{
					break;
				}

				if (reader.TokenType != JsonTokenType.PropertyName)
				{
					continue;
				}

				string propertyName = reader.GetString();
				reader.Read(); // 移动到属性值

				switch (propertyName)
				{
					case "Name":
						name = reader.GetString();
						break;
					case "Value":
						value = reader.GetString();
						break;
					case "Domain":
						domain = reader.GetString();
						break;
					case "Path":
						path = reader.GetString();
						break;
					case "Expiry":
						if (reader.TokenType != JsonTokenType.Null)
						{
							string expiryString = reader.GetString();
							if (DateTime.TryParse(expiryString, out DateTime tempExpiry))
							{
								expiry = tempExpiry;
							}
						}
						break;
					case "Secure":
						secure = reader.GetBoolean();
						break;
					case "IsHttpOnly":
						httpOnly = reader.GetBoolean();
						break;
				}
			}

			// 确保必要的属性已设置
			if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(value))
			{
				throw new JsonException("Cookie缺少必要的属性（Name或Value）");
			}

			// 使用适当的构造函数创建Cookie对象
			return new Cookie(name, value, domain, path, expiry);
		}

		public override void Write(Utf8JsonWriter writer, Cookie cookie, JsonSerializerOptions options)
		{
			writer.WriteStartObject();

			writer.WriteString("Name", cookie.Name);
			writer.WriteString("Value", cookie.Value);
			writer.WriteString("Domain", cookie.Domain);
			writer.WriteString("Path", cookie.Path);
			writer.WriteString("Expiry", cookie.Expiry?.ToString("O"));
			writer.WriteBoolean("Secure", cookie.Secure);
			writer.WriteBoolean("IsHttpOnly", cookie.IsHttpOnly);

			writer.WriteEndObject();
		}
	}
}
